const app = getApp();
const pageSize = 20;


const payStatus=[
  {
    value:"",
    name:"全部"
  },
  {
    value:1,
    name:"已支付"
  },
  {
    value:2,
    name:"未支付"
  }
];
const payTypes = [{
  value: 0,
  name: '全部'
}, {
  value: 1,
  name: '微信支付'
}, {
  value: 2,
  name: '实体卡支付'
}, {
  value: 3,
  name: '电子卡支付'
}, {
  value: 4,
  name: '积分支付'
}, {
  value: 5,
  name: '投币支付'
}, {
  value: 6,
  name: '支付宝支付'
}];
Page({
  data: {
    payStatus,
    conditions: {
      order_number: "",
      equipment_name: "",
      start_time: "",
      end_time: "",
      card_number: "",
      village_name: "",
      payTypeIndex: "",
      payStatusIndex:1
    },
    drawer: false,
    isFilter: true,
    empty: false,
    loadmore: false,
    nomore: false,
    list: [],
    payTypes,
    villages: [],
    refund_number: 0,
    pay_number: 0,
    total: 0,
    total_money: 0,
    refund_sum: 0,
    total_integral: 0,
    isRepair: false, //是否是维修员
  },

  //获取本月的开始日期
  getMonthOfStart() {
    let date = new Date();
    let startDate = date.getFullYear() + "-" + ((date.getMonth() + 1) < 10 ? "0" : "") + (date.getMonth() + 1) + "-" + "01";
    return startDate;
  },

  //获取本月的结束日期
  getMonthOfEnd() {
    let date = new Date();
    let currentMonth = date.getMonth();
    let nextMonth = ++currentMonth;
    let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
    let oneDay = 1000 * 60 * 60 * 24;
    let lastDate = new Date(nextMonthFirstDay - oneDay);
    let endDate = lastDate.getFullYear() + "-" + ((lastDate.getMonth() + 1) < 10 ? "0" : "") + (lastDate.getMonth() + 1) + "-" + (lastDate.getDate() < 10 ? "0" : "") + lastDate.getDate();
    return endDate;
  },

  onLoad: function (options) {
    let navTitle = "订单管理";
    this.is_franchiser = options.is_franchiser || "";
    if (options.type == 1) {
      navTitle = "消费记录";
      this.equipment_control_id = options.id
    }
    this.setData({
      isRepair: options.is_repair == 1 ? true : false,
      pageType: options.type || 0, //0订单管理 1消费记录
      "conditions.start_time": this.getMonthOfStart(),
      "conditions.end_time": this.getMonthOfEnd()
    })
    wx.setNavigationBarTitle({
      title: navTitle
    })
    this.page = 1;
    this.getConsumeRecord();

    // if (this.data.pageType == 0) {
    //   if (this.is_franchiser == 1) {
    //     this.getFranchiserVillage();
    //   } else {
    //     this.getVillages();
    //   }
    // }
  },

  initialFixedHeight() {
    const query = wx.createSelectorQuery();
    query.select('.fixed-total').boundingClientRect((rect) => {
      this.setData({
        FixedHeight: rect.height
      })
    }).exec();
  },

  reloadData() {
    this.page = 1;
    this.setData({
      loadmore: false,
      nomore: false,
      list: [],
      total: 0,
      refund_number: 0,
      refund_sum: 0,
      pay_number: 0,
      total_money: 0,
      total_integral: 0,
    })
    wx.showLoading()
    this.getConsumeRecord();
  },

  showDrawer() {
    this.condition = {
      ...this.data.conditions
    };
    this.setData({
      drawer: true,
    })
  },

  closeDrawer() {
    this.setData({
      drawer: false,
      conditions: this.condition
    })
    delete(this.condition)
  },

  resetDrawer() {
    const conditions = this.data.conditions;
    for (let x in conditions) {
      if (x == "start_time") {
        conditions[x] = this.getMonthOfStart();
      } else if (x == "end_time") {
        conditions[x] = this.getMonthOfEnd();
      } else {
        conditions[x] = "";
      }
    }
    this.setData({
      conditions,
    })
  },
  confirmDrawer() {
    let isFilter = false;
    const conditions = this.data.conditions;
    for (let x in conditions) {
      conditions[x] !== "" && (isFilter = true);
    }
    this.setData({
      isFilter
    })
    delete(this.condition);
    this.reloadData();
  },

  onPullDownRefresh: function () {
    this.reloadData();
  },

  onReachBottom: function () {
    if (this.data.loadmore) {
      ++this.page;
      this.getConsumeRecord()
    }
  },


  //获取消费记录
  getConsumeRecord() {
    const conditions = this.data.conditions;
    let param = {
      page: this.page,
      pageSize,
      start_time: conditions.start_time,
      end_time: conditions.end_time,
      pay_type: conditions.payTypeIndex !== "" ? this.data.payTypes[conditions.payTypeIndex].value : "",
      pay_status: conditions.payStatusIndex !== "" ? this.data.payStatus[conditions.payStatusIndex].value : "",
      village_id: this.village_id || "",
      sale_number: conditions.order_number,
      equipment_name: conditions.equipment_name,
      card_number: conditions.card_number,
      phone:conditions.phone
    }
    if (this.data.pageType == 1) {
      param.equipment_control_id = this.equipment_control_id;
    }
    if (this.is_franchiser && this.is_franchiser == 1) {
      param.is_franchiser = 1
    }

    let url = "Partner/OrderList/sell_water";
    if (this.data.isRepair) {
      url = "Manage/Equipment/sell_water";
    }
    app.ajax({
      url,
      data: param,
      success: res => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        const code = res.data.code;
        if (code === 1000) {
          const source = res.data.data;
          let list = this.data.list.concat(source.order);
          this.setData({
            empty: false,
            refund_number: source.return_num,
            refund_sum: source.refund_sum,
            pay_number: source.pay_num,
            total: source.count,
            list,
            drawer: false,
            loadmore: list.length < source.count ? true : false,
            nomore: list.length >= source.count ? true : false,
            total_money: source.sum,
            total_integral: source.integral
          })
        } else if (code == -1003) {
          this.setData({
            nomore: true,
            loadmore: false,
            empty: this.page == 1 ? true : false,
            drawer: false,
          })
          this.initialFixedHeight();
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        app.showToast("网络错误")
      }
    })
  },


  handlePayType(e) {
    const {
      name,
      index
    } = e.currentTarget.dataset;
    this.setData({
      [`conditions.${name}`]: index
    })
  },

  handleCondition(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`conditions.${name}`]: e.detail.value
    })
  },



  //跳转到选择园区
  navMiddleVillage() {
    let _self = this;
    let url = "../middle/village/index?hidden=1";
    if (this.is_franchiser) {
      url += '&is_franchiser&mode=1'
    }
    wx.navigateTo({
      url,
      events: {
        acceptDataFromMiddleVillage: function (data) {
          if (data) {
            _self.village_id = data.id;
            _self.setData({
              [`conditions.village_name`]: data.village_name
            })
          }
        }
      },
      success: res => {
        res.eventChannel.emit("acceptDataFromOpenerPage", {
          village_id: this.village_id || ''
        })
      }
    })
  },


  getVillages() {
    app.ajax({
      url: "Partner/WaterCard/getPartnerVillage",
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            villages: res.data.data
          })
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },

  //获取加盟商的园区列表
  getFranchiserVillage() {
    app.ajax({
      url: "Partner/Franchiser/FranchiserVillageList",
      data: {
        page: 1,
        row: 1000
      },
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            villages: res.data.data.data
          })
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  }
})